# -*- coding: utf-8 -*-

import click
from flask import Flask, render_template
from .controllers import bpcontrollers
from .views import bpviews
from .commands import appcommands
from .extensions import init_extensions
from configs import config

def create_app(config_name=None):
    if config_name is None:
        config_name = 'default'

    app = Flask(__name__)
    app.config.from_object(config[config_name])

    init_extensions(app)

    # controllers
    for bp in bpcontrollers:
        app.register_blueprint(bp)

    # views
    for bp in bpviews:
        app.register_blueprint(bp)

    @app.errorhandler(400)
    def bad_request(e):
        return render_template('errors/400.html'), 400

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('errors/404.html'), 404

    @app.errorhandler(500)
    def internal_server_error(e):
        return render_template('errors/500.html'), 500

    # commands
    @app.cli.command("greet")
    @click.option('--name', default='World')
    def greet(name):
        click.echo(f'Hello, {name}!')

    for cli in appcommands:
        app.cli.add_command(cli)

    return app